import allure
import requests

from common.log_tools import log
from common.yaml_tools import YamlTools
from config.conf import API_URL

class BaseRequest:
    sess = requests.session()

    @classmethod
    def send_request(cls,**kwargs):
        try:
            rp =  cls.sess.request(**kwargs)
        except Exception as e:
            log.error(e)
        else:
            return rp
     # 执行接口测试方法
    @classmethod
    def excute_api_request(cls,request,parametrize):
        #接口请求方式
        method =  request['method']
        #把请求方式输出在allure报告中
        allure.attach(method,'请求方法:',attachment_type=allure.attachment_type.TEXT)
        #接口的url地址
        url = request["url"]
        url = API_URL+url
        print(url)
        allure.attach(url,'接口地址:',attachment_type=allure.attachment_type.TEXT)
        #接口的cookie
        cookies = request["cookies"]
        if cookies is not None:
           allure.attach(cookies,'cookies:',attachment_type=allure.attachment_type.TEXT)
        #接口的请求头
        headers = request['headers']
        if headers is not None:
           allure.attach(headers,'headers:',attachment_type=allure.attachment_type.TEXT)
        #接口的parasm参数
        params = parametrize["params"]
        if params is not None:
           allure.attach(str(params),'params:',attachment_type=allure.attachment_type.TEXT)
        #接口的data参数
        data = parametrize["data"]
        if data is not None:
           allure.attach(str(data),'data:', attachment_type=allure.attachment_type.TEXT)
        #接口的json参数
        json = parametrize["json"]
        if json is not None:
           allure.attach(str(json), 'json:',attachment_type=allure.attachment_type.TEXT)
        #接口的file参数
        files = parametrize["files"]
        if files is not None:
           allure.attach(str(files), '文件',attachment_type=allure.attachment_type.TEXT)
        #接口的预期结果
        expect =parametrize["expect"]
        if expect is not None:
           allure.attach(expect,'预期结果:',attachment_type=allure.attachment_type.TEXT)
        #执行接口测试发送请求
        rp = cls.send_request(method=method,url=url,headers=headers,cookies=cookies,params=params,data=data,json=json,files=files)
        print('我是rp',rp)
        if rp is not None:
           allure.attach(rp.text,'实际结果:',attachment_type=allure.attachment_type.TEXT)
        return rp
if __name__ == '__main__':
    api_login_data = YamlTools.read_yaml_file("api\\api_login.yaml")[0]
    print(api_login_data)
    rp = BaseRequest.excute_api_request(api_login_data['request'],api_login_data['parametrize'][0])
    print(rp.text)